# coding=utf-8
import os
import re
import time
import logging
import json
import urllib3

import requests
from bs4 import BeautifulSoup

def get_url_list():
    """
    获取所有URL目录列表
    :return:
    """

    # 90后标签下面的分类
    # 获取music list 列表
    second_host = "http://nplserver.kuwo.cn"
    second_uri = "/pl.svc?op=getlistinfo&pid=3550328000&pn=0&rn=30&encode=utf8&keyset=pl2012&vipver=MUSIC_9.1.1.2_BCS2&newver=1"
    second_response = requests.get(second_host + second_uri)
    second_soup = BeautifulSoup(second_response.content, "html.parser")
    secondRespJson = json.loads(second_soup.text)
    music_list = secondRespJson['musiclist']
    num = 1
    for j in range(len(music_list)):
        song_info = music_list[j]
        song_info_id = song_info["id"]
        song_download_host = "http://mobi.kuwo.cn"
        #  歌曲下载url
        song_download_info = "/mobi.s?f=web&source=kwplayerhd_ar_4.3.0.8_tianbao_T1A_qirui.apk&type=convert_url_with_sign&rid=" + song_info_id + "&br=2000kflac"
        song_name = song_info['name']
        song_artist = song_info['artist']
        try:
            third_response = requests.get(song_download_host + song_download_info)
            third_soup = BeautifulSoup(third_response.content, "html.parser")

            third_resp_json = json.loads(third_soup.text)
            song_final_download_url = third_resp_json['data']['url']
            # f = urllib3.urlopen(song_final_download_url)
            # with open(song_artist+"_"+song_name+".flac", "wb") as code:
            #     code.write(f.read())

            http = urllib3.PoolManager()
            response = http.request('GET', song_final_download_url)
            # 先判断目录是否存在，不存在则创建
            rstr = r"[\/\\\:\*\?\"\<\>\|]"  # '/ \ : * ? " < > |'
            new_title = re.sub(rstr, "_", "欧美流行_三秒沦陷")
            path = "D:\music\\" + new_title + "\\"
            if os.path.isdir(path):
                # print('文件夹已存在')
                pass
            else:
                os.makedirs(path)
            song_full_path = path + song_artist + "_" + song_name + ".flac"
            num = num + 1
            print(str(num) + ":  " + song_full_path)

            with open(song_full_path, "wb") as f:
                f.write(response.data)
        except Exception as e:
            print("下载异常", e)


def main():
    start = time.time()
    get_url_list()

    total_time = time.time() - start
    print(u"总共耗时：%f 秒" % total_time)


if __name__ == '__main__':
    main()
